import 'package:edu/constants/app_images.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/common/course_list_cell_widget.dart';
import 'package:edu/pages/course/course_search/course_search_page_logic.dart';
import 'package:edu/utils/app_router.dart';
import 'package:edu/utils/app_theme.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:tuple/tuple.dart';

class CourseSearchPage extends StatefulWidget {
  const CourseSearchPage({super.key});

  @override
  State<CourseSearchPage> createState() => _CourseSearchPageState();
}

class _CourseSearchPageState extends State<CourseSearchPage> {
  @override
  void initState() {
    super.initState();
    context.read<CourseSearchPageLogic>().init();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(context),
      body: _buildMainBody(context),
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    return AppBar(
      title: Container(
        height: 36,
        width: 320,
        decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.surface,
          borderRadius: BorderRadius.circular(18),
        ),
        child: Selector<CourseSearchPageLogic, bool>(
          selector: (context, logic) => logic.textController.text.isNotEmpty,
          builder: (context, v, child) {
            final logic = context.read<CourseSearchPageLogic>();
            final tipColor = v
                ? null
                : AppTheme.shared.appBarSearchTextTipColor;
            // 输入框有值时会出现X图标,点击可清空输入框
            return TextField(
              controller: logic.textController,
              decoration: InputDecoration(
                hintText: AppStrings.searchHint,
                border: InputBorder.none,
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: 4,
                  vertical: 4,
                ),
                prefixIcon: Icon(Icons.search, color: tipColor),
                suffixIcon: v
                    ? IconButton(
                        onPressed: logic.clearSearchText,
                        icon: const Icon(Icons.close),
                      )
                    : null,
              ),
              // 获取焦点并自动聚焦
              focusNode: logic.focusNode,
              autofocus: true,
              textInputAction: TextInputAction.done,
              // 输入完成时调用
              onSubmitted: (text) {
                logic.insertSearchText(text.trim());
              },
            );
          },
        ),
      ),
      actions: const [],
    );
  }

  Widget _buildMainBody(BuildContext context) {
    return Selector<CourseSearchPageLogic, bool>(
      selector: (_, logic) => logic.isCourseEmpty,
      builder: (context, v, child) {
        if (v) {
          return Selector<CourseSearchPageLogic, bool>(
            selector: (context, logic) => logic.isSearchTextEmpty,
            builder: (context, v, child) {
              if (v) {
                return Column(
                  children: [
                    _SearchHistory(),
                    const SizedBox(height: 16),
                    Expanded(child: _HotSearch()),
                  ],
                );
              } else {
                return Center(
                  child: Image.asset(AppImages.noContent, fit: BoxFit.cover),
                );
              }
            },
          );
        } else {
          return _buildContentList(context);
        }
      },
    );
  }

  Widget _buildContentList(BuildContext context) {
    return Selector<CourseSearchPageLogic, Tuple2<int, bool>>(
      selector: (_, logic) => Tuple2(logic.courses.length, logic.canLoadMore),
      builder: (context, v, child) {
        final logic = context.read<CourseSearchPageLogic>();
        final courses = logic.courses;
        final canLoadMore = v.item2;

        if (canLoadMore) {
          return ListView.builder(
            controller: logic.scrollController,
            itemCount: courses.length + 1,
            itemBuilder: (context, index) {
              if (index == courses.length) {
                if (canLoadMore) {
                  return const CourseLoadingCellWidget();
                } else {
                  final course = courses[index];
                  return CourseListCellWidget(
                    course: course,
                    onTap: () {
                      context.pushNamed(
                        AppRouter.kCourseDetail,
                        queryParameters: {'id': '${course.id}'},
                      );
                    },
                  );
                }
              } else {
                final course = courses[index];
                return CourseListCellWidget(course: course);
              }
            },
          );
        } else {
          return ListView.builder(
            controller: logic.scrollController,
            itemCount: courses.length,
            itemBuilder: (context, index) {
              final course = courses[index];
              return CourseListCellWidget(
                course: course,
                searchKey: logic.searchKey,
                onTap: () {
                  context.pushNamed(
                    AppRouter.kCourseDetail,
                    queryParameters: {'id': '${course.id}'},
                  );
                },
              );
            },
          );
        }
      },
    );
  }
}

// 热门搜索
class _HotSearch extends StatelessWidget {
  const _HotSearch();

  @override
  Widget build(BuildContext context) {
    return Selector<CourseSearchPageLogic, List<String>?>(
      selector: (context, logic) => logic.topCourseKeys,
      builder: (context, keys, child) {
        return _buildMainBody(context, keys);
      },
    );
  }

  Widget _buildMainBody(BuildContext context, List<String>? keys) {
    if (keys == null && keys!.isEmpty) {
      // 暂无数据,返回无限小的部件
      return const SizedBox.shrink();
    }

    final topKeys = keys;
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            AppStrings.hotSearch,
            style: Theme.of(context).textTheme.bodyLarge,
          ),
          const SizedBox(height: 16),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10),
              child: GridView.builder(
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 8,
                  crossAxisSpacing: 8,
                  mainAxisSpacing: 8,
                ),
                itemCount: topKeys.length,
                itemBuilder: (context, index) {
                  return GestureDetector(
                    onTap: () {
                      final key = topKeys[index];
                      context.read<CourseSearchPageLogic>().updateSearchText(
                        key,
                      );
                    },
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          width: 5,
                          height: 5,
                          decoration: BoxDecoration(
                            color: Theme.of(context).colorScheme.primary,
                            shape: BoxShape.circle,
                          ),
                        ),
                        const SizedBox(width: 8),
                        Text(
                          topKeys[index],
                          style: Theme.of(context).textTheme.bodySmall,
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// 搜索历史记录
class _SearchHistory extends StatelessWidget {
  const _SearchHistory();

  @override
  Widget build(BuildContext context) {
    return Selector<CourseSearchPageLogic, bool>(
      selector: (context, logic) => logic.isSearchHistoryEmpty,
      builder: (context, v, child) {
        if (v) {
          return const SizedBox.shrink();
        } else {
          return _buildMainBody(context);
        }
      },
    );
  }

  Widget _buildMainBody(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                AppStrings.searchHistory,
                style: Theme.of(context).textTheme.bodyLarge,
              ),
              const Spacer(),
              GestureDetector(
                onTap: () {
                  // 清空搜索历史记录
                  context.read<CourseSearchPageLogic>().clearSearchHistories();
                },
                child: Icon(
                  Icons.delete_forever,
                  color: Colors.grey[500],
                  size: 20,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Selector<CourseSearchPageLogic, List<String>>(
            selector: (context, logic) => logic.searchHistories,
            builder: (context, v, child) {
              return Wrap(
                spacing: 8,
                runSpacing: 8,
                children: v.map((text) {
                  return GestureDetector(
                    onTap: () {
                      // 搜索
                      context.read<CourseSearchPageLogic>().updateSearchText(
                        text,
                      );
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: Theme.of(
                          context,
                          // ignore: deprecated_member_use
                        ).colorScheme.primary.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Text(
                        text,
                        style: Theme.of(context).textTheme.bodySmall,
                      ),
                    ),
                  );
                }).toList(),
              );
            },
          ),
        ],
      ),
    );
  }
}
